package com.situ.user.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.situ.user.bean.Address;
import com.situ.user.bean.Order;
import com.situ.user.bean.User;
import com.situ.user.service.AddressService;
import com.situ.user.service.OrderService;

@Controller
@RequestMapping("/user/order")
public class OrderController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private AddressService addressService;

	// 添加订单
	@PostMapping("/add")
	public String add(@RequestParam("cartId") Integer[] cartIds, HttpSession session, Model model) {
		// 取出用户的id
		User user = (User) session.getAttribute("user");
		// 调用Service
		try {
			// 查询地址信息
			List addresses = addressService.getByUserId(user.getId());
			model.addAttribute("addresses", addresses);
			Order order = orderService.add(user.getId(), cartIds);
			// 生成成功
			model.addAttribute("order", order);
			return "user/order";
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("erroe", e.getMessage());
			return "user/error";
		} finally {

		}
	}

	// 支付操作
	@GetMapping("/pay")
	public String pay(String orderId, Integer addressId, Model model) {

		// 1根据订单id查询订单信息
		Order order = orderService.getById(orderId);
		// 利用model
		model.addAttribute("order", order);
		// 2根据订单的Id查询地址信息
		Address address = addressService.getById(addressId);
		// 利用model
		model.addAttribute("address", address);
		// 将收货地址写入数据库中
		order.setAddressId(addressId);
		orderService.update(order);
		return "user/pay";
	}

	@PostMapping("/pay")
	public String pay(String id, String paypwd, HttpSession session, Model model) {
		// 获取用户的信息
		User user = (User) session.getAttribute("user");
		try {
			int result = orderService.pay(id, paypwd, user.getId());
			// 支付成功
			return "redirect:/user/order/list";
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "user/error";
		}
	}

	@GetMapping("/list")
	public String get() {
		return "user/orderList";
	}

}
